<!--会议室预约-->
<template>
  <div class="container">
    <!-- 项目表格 -->
    <div class="table-container" >
      <el-table :data="projTableData"
                style="width: 200px; height: 600px"
                highlight-current-row
                @current-change="handleCurrentChange">
        <el-table-column label="项目编号" prop="projectNumber"></el-table-column>
        <el-table-column label="项目名称" prop="projectName"></el-table-column>
      </el-table>
    </div>

    <!-- 会议室表格 -->
    <div class="table-container">
      <div style="display: flex; max-height: 20px;">
        <h5 style="margin-left: 10px">会议地点</h5>
        <el-input style="margin-top: -5px; width:80px; margin-left: 10px" placeholder="请输入" v-model="meetLoca"></el-input>
        <h5 style="margin-left: 20px">项目名称</h5>
        <el-input style="margin-top: -5px; width:80px; margin-left: 10px" placeholder="请输入" v-model="projectName" ></el-input>
        <h5 style="margin-left: 20px">联系人姓名</h5>
        <el-input style="margin-top: -5px; width:130px; margin-left: 10px" placeholder="请输入联系人姓名" v-model="contactPerson" ></el-input>
        <el-button type="primary" style="margin-top: -5px; margin-left: 20px" icon="el-icon-search" @click="init">查询</el-button>
        <el-button type="warning" style="margin-top: -5px; margin-left: 10px" icon="el-icon-refresh" @click="reset">重置</el-button>
        <el-button @click="exportToExcel" type="success" style="margin-top: -5px; margin-left: 10px">导出会议为Excel</el-button>
      </div>
      <el-table :data="meetTableData" style="width: 1000px; height: 500px;margin-top: 10px" id="data-table">
        <el-table-column label="会议室预约" header-align="center" :label-class-name="'large-header'">
          <el-table-column label="时间" prop="meetTime"></el-table-column>
          <el-table-column label="星期" prop="weekday"></el-table-column>
          <el-table-column label="地点" prop="meetLoca"></el-table-column>
          <el-table-column label="项目" prop="projectName"></el-table-column>
          <el-table-column label="联系人" prop="contactPerson"></el-table-column>
          <el-table-column label="电话" prop="contactPhone"></el-table-column>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="添加会议室预约" :visible.sync="dialogVisible" width="600px">
      <el-form :model="formData" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="时间" required>
              <el-date-picker
                  v-model="formData.formMeet.meetTime"
                  type="datetime"
                  placeholder="请选择时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="地点" required>
              <el-input v-model="formData.formMeet.meetLoca" placeholder="请填写会议室地点"></el-input>
            </el-form-item>
          </el-col>
<!--          <el-col :span="24">
            <el-form-item label="开标时间" required>
              <el-date-picker
                  v-model="form.openingTime"
                  type="datetime"
                  placeholder="请选择开标时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
          </el-col>-->
          <el-col :span="24">
            <el-form-item label="联系部门" required>
              <el-input v-model="formData.form.department" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系人" required>
              <el-input v-model="formData.form.name" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系电话" required>
              <el-input v-model="formData.form.phoneNumber" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formData.formMeet.meetMemo" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <div style="text-align: center; margin-top: 20px;">
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {addProject,getProjectsByStatus} from '@/api/project'
import {getUserByName, getUserByUsername} from "@/api/user";
import {addMeet, getMeetListBySome, getMeetListByStatus} from "@/api/meet";
import ExcelJS from 'exceljs';

export default {
  data() {
    return {
      projTableData: [],
      meetTableData: [],
      dialogVisible: false,
      formData:{
        form: {},
        formMeet: {},
      },
      updateStatus: {},
      projectName: '',
      meetLoca: '',
      meetTime: '',
      contactPerson: '',

    }
  },
  methods: {
    init() {
      getProjectsByStatus(2,2).then(res => {
        this.projTableData = res
      })
      getMeetListBySome(this.meetLoca,this.projectName,this.contactPerson,1).then(res => {
        this.meetTableData = res
        const days = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
        this.meetTableData = res.map(item => {
          const dateObj = new Date(item.meetTime);
          return {
            meetTime: item.meetTime,
            projectName: item.projectName,
            meetLoca: item.meetLoca,
            contactPerson: item.contactPerson,
            contactPhone: item.contactPhone,
            weekday: days[dateObj.getDay()], // 添加一个 `weekday` 字段表示星期
          };
        });
      })
    },
    handleCurrentChange(val) { // 点击项目表格行
      this.projectNumber = val.projectNumber
      getUserByName(val.tenderOfficer).then(res => {
        this.formData.form = res
        this.projectName = val.projectName
      })
      this.dialogVisible=true
    },
    async handleSubmit() { // 提交会议室预约
      this.formData.formMeet.projectName = this.projectName // 将项目名称赋值给formMeet
      this.formData.formMeet.contactPhone = this.formData.form.phoneNumber // 将联系方式赋值给formMeet
      this.formData.formMeet.contactPerson = this.formData.form.name   // 将联系人赋值给formMeet
      this.formData.formMeet.status = 1
      await addMeet(this.formData.formMeet).then(res => { // 提交表单
        if(res){
          this.$message({
            message: '预约成功',
            type: 'success'
          })
        }
      })
      this.updateStatus.projectNumber = this.projectNumber
      this.updateStatus.annoStatus = 3
      this.updateStatus.meetingRoom = this.formData.formMeet.meetLoca
      await addProject(this.updateStatus)
      this.dialogVisible = false; // 提交后关闭对话框
      this.init(); // 刷新表格数据
    },
    // 导出会议室预约表格为Excel
    async exportToExcel() {

      const workbook = new ExcelJS.Workbook();
      const worksheet = workbook.addWorksheet('Sheet1');

      // 在表格最上方插入“会议室预约”这一行
      worksheet.mergeCells('A1:G1');  // 表格有 8 列（A 到 H）
      const titleCell = worksheet.getCell('A1');
      titleCell.value = '会议室预约';
      titleCell.alignment = { horizontal: 'center', vertical: 'middle' };
      titleCell.font = { size: 16, bold: true };

      // 设置表头
      const headerRows = document.querySelectorAll('#data-table thead th');
      const headerValues = [];

      // 添加“日期”和“开标时间”列
      headerValues.push("日期", "开标时间");

      // 遍历表头单元格，并跳过第一个字段（索引从1开始）
      headerRows.forEach((cell, index) => {
        if (index > 2) {  // 跳过第一个字段（索引0）
          headerValues.push(cell.textContent.trim());
        }
      });
      worksheet.addRow(headerValues);  // 添加表头行
      // 获取表格数据行
      const rows = document.querySelectorAll('#data-table tbody tr');
      rows.forEach(row => {
        const cells = row.querySelectorAll('td');
        const rowValues = [];

        cells.forEach((cell, index) => {
          let cellValue = cell.textContent.trim();

          // 格式化“时间”列
          if (index === 0) {  // 假设“时间”列是第一列
            const date = new Date(cellValue);
            if (!isNaN(date.getTime())) {
              // 获取日期部分（年月日）
              const dateStr = date.toLocaleDateString('zh-CN');

              // 获取时分秒部分
              const timeStr = this.formatTime(date);  // 调用格式化时间的方法

              // 将日期和时分秒分别添加到不同的列
              rowValues.push(dateStr, timeStr);  // 添加日期和开标时间列
            } else {
              rowValues.push('', '');  // 如果日期无效，则插入空值
            }
          }

          // 对于其他列，直接推送单元格值
          else {
            rowValues.push(cellValue);
          }
        });

        worksheet.addRow(rowValues);  // 添加数据行
      });

      // 将数据写入 Excel 文件并下载
      const buffer = await workbook.xlsx.writeBuffer();
      const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = '会议室预约.xlsx';
      link.click();
    },
    // 时间格式化方法，转换成“下午3:00”这样的格式
    formatTime(date) {
      const hours = date.getHours();
      const minutes = date.getMinutes();
      const period = hours >= 12 ? '下午' : '上午';  // 判断是上午还是下午
      const hour12 = hours % 12 || 12;  // 12小时制，如果小时为0则为12（午夜12点）
      const minuteStr = minutes < 10 ? '0' + minutes : minutes;  // 补充零，保持两位数分钟

      return `${period}${hour12}:${minuteStr}`;  // 返回格式化的时间
    },
    reset() { // 重置
      this.meetLoca = "";
      this.projectName = "";
      this.contactPerson = "";
      this.init();
    },

  },
  created() {
    this.init()
  }
}
</script>

<style  scoped>
/* 使用flex布局，使两个表格并排显示 */
.container {
  display: flex;
  justify-content: space-between; /* 两个表格之间留有空间 */
  gap: 20px; /* 设置表格之间的间距 */
}

.table-container {
  background-color: #f9f9f9; /* 设置表格背景色 */
  padding: 10px; /* 为表格添加内边距 */
  border-radius: 8px; /* 设置表格的圆角 */
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1); /* 设置阴影效果 */
  height: 550px;
  overflow-y: auto; /* 使表格超出时可以上下滚动 */
}

>>> .large-header {
  font-size: 18px; /* 设置字体大小 */
  font-weight: bold; /* 可选，设置字体加粗 */
}
</style>